package com.xuchaotong.zk.server.service.impl;

import com.xuchaotong.zk.server.demo.ZookeeperMgr;
import com.xuchaotong.zk.server.service.NotifyZookeeperService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.rmi.RemoteException;

/**
 * @author 311633
 * @version 1.0
 * @ClassName:
 * @Description:
 * @date 2017/11/20 16:25
 */
@Service
public class NotifyZookeeperServiceImpl implements NotifyZookeeperService, InitializingBean, DisposableBean {
    private static final Logger LOG = LoggerFactory.getLogger(NotifyZookeeperServiceImpl.class);
    private static boolean isInit = false;

    public void destroy() throws Exception {
        ZookeeperMgr.getInstance().release();
    }

    public synchronized void afterPropertiesSet() throws Exception {
        LOG.info("init....");
        if (!isInit) {
            ZookeeperMgr.getInstance().init("127.0.0.1:2181", "", false);
            isInit = true;
        }
    }

    public String notifyZookeeper(String path, String val) {
        try {
            boolean isExist = ZookeeperMgr.getInstance().exists(path);
            if (!isExist) {

                LOG.info(path + " not exist. not update ZK.");

            } else {
                //
                // 通知
                //
                ZookeeperMgr.getInstance().writePersistentUrl(path, val);
            }

        } catch (Exception e) {

            LOG.error(e.toString(), e);
//            throw new RemoteException("zk.notify.error", e);
        }

        return "SUCCESS";
    }
}
